﻿////////////////////////////////////////////////
///功能：公共函数库
///编写人：龙华超
///编写日期：2005-9-20
///最后修改人：龙华超
///最后修改日期：2006-2-11
///注意事项：
///////////////////////////////////////////////

using System;
using System.Web;
using System.Web.UI;
using System.Text.RegularExpressions;
using System.Text;
using System.Net.Mail;
using System.Web.Util;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Resources;

namespace Common
{
    /// <summary>
    /// Function 的摘要说明。
    /// </summary>
    public class Common_Function
    {


        #region CheckBoxList控件
        /// <summary>
        /// CheckBoxList控件
        /// </summary>
        /// <param name="_ObjectName"></param>
        /// <param name="_SelectValue"></param>
        public static void CheckBoxListSelect(System.Web.UI.WebControls.CheckBoxList _ObjectName, string _SelectValue)
        {
            if (_SelectValue.Trim().Length > 0)
            {
                foreach (System.Web.UI.WebControls.ListItem SelItem in _ObjectName.Items)
                {
                    if (SelItem.Value.Trim() == _SelectValue.Trim())
                    {
                        SelItem.Selected = true;
                    }
                }
            }
        }

        public static void CheckBoxListBind(System.Web.UI.WebControls.CheckBoxList _ObjectName, System.Data.DataTable dt,
            string valueField, string textField)
        {
            _ObjectName.Items.Clear();
            _ObjectName.DataSource = dt.DefaultView;
            _ObjectName.DataValueField = valueField;
            _ObjectName.DataTextField = textField;
            _ObjectName.DataBind();
        }

        #endregion

        #region RadioButtonList控件
        /// <summary>
        /// RadioButtonList控件
        /// </summary>
        /// <param name="_ObjectName"></param>
        /// <param name="_SelectValue"></param>
        public static void RadioButtonListSelect(System.Web.UI.WebControls.RadioButtonList _ObjectName, string _SelectValue)
        {

            if (_SelectValue.Trim().Length > 0)
            {
                int i = 0;
                foreach (System.Web.UI.WebControls.ListItem SelItem in _ObjectName.Items)
                {
                    if (SelItem.Value.Trim() == _SelectValue.Trim())
                    {
                        _ObjectName.SelectedIndex = i;
                        break;
                    }
                    i = i + 1;
                }
            }
        }

        public static void RadioButtonListBind(System.Web.UI.WebControls.RadioButtonList _ObjectName, System.Data.DataTable dt,
            string valueField, string textField, string _SelectValue)
        {
            _ObjectName.Items.Clear();
            _ObjectName.DataSource = dt.DefaultView;
            _ObjectName.DataValueField = valueField;
            _ObjectName.DataTextField = textField;
            _ObjectName.DataBind();
            bool isSelected = false;

            if (_SelectValue.Trim().Length > 0)
            {
                int i = 0;


                foreach (System.Web.UI.WebControls.ListItem SelItem in _ObjectName.Items)
                {
                    if (SelItem.Value.Trim() == _SelectValue.Trim())
                    {
                        _ObjectName.SelectedIndex = i;
                        isSelected = true;
                        break;
                    }
                    i = i + 1;
                }

            }
        }
        #endregion

        #region 返回整数
        public static string GetInt(string sDecimal)
        {
            string sReturn = "";

            int iPoint = sDecimal.IndexOf('.', 0);

            if (iPoint > -1)
            {
                sReturn = sDecimal.Substring(0, sDecimal.IndexOf('.', 0));
            }
            else
            {
                sReturn = sDecimal;
            }

            return sReturn;
        }
        #endregion

        #region 去0
        public static string DecimalTrim(string sDecimal)
        {
            if (sDecimal.IndexOf('.', 0) > -1)
            {
                int iZero = 0;

                for (int i = sDecimal.Length - 1; i >= 0; i--)
                {
                    if (sDecimal.Substring(i, 1) == "0")
                    {
                        iZero = iZero + 1;
                    }
                    else
                    {
                        break;
                    }
                }
                if (iZero > 0)
                {
                    sDecimal = sDecimal.Substring(0, sDecimal.Length - iZero);
                }
                if (sDecimal.Substring(sDecimal.Length - 1, 1) == ".")
                {
                    sDecimal = sDecimal.Substring(0, sDecimal.Length - 1);
                }
            }

            return sDecimal;
        }
        #endregion

        #region 返回一定长度的字符串
        /// <summary>
        /// 返回一定长度的字符串
        /// </summary>
        /// <param name="LineString"></param>
        /// <param name="CharNum"></param>
        /// <returns></returns>
        public static string StringNum(string LineString, int CharNum)
        {
            string Rt = "";
            if (CharNum == 0)
            {
                Rt = LineString;
            }
            else
            {
                if (CharNum < LineString.Length)
                {
                    Rt = LineString.Substring(0, CharNum);
                }
                else
                {
                    Rt = LineString;
                }

            }

            return Rt;
        }

        #endregion

        #region 转换字符串，将转换C#中的空格及加车符为html格式
        /// <summary>
        /// 转换字符串，将转换C#中的空格及加车符为html格式
        /// </summary>
        /// <param name="str">原字符串</param>
        /// <returns>转换后的字符串</returns>
        public static string ConvertString(string str)
        {
            str = str.Replace("\n", "<br>");
            str = str.Replace(" ", " ");
            return str;
        }
        #endregion

        #region 验证电子邮件地址
        /// <summary>
        /// 验证电子邮件地址
        /// </summary>
        /// <param name="emailAddress">待验证的电子邮件地址</param>
        /// <returns>电子邮件地址是否合法</returns>
        public static bool ValidateEmailAddress(string emailAddress)
        {
            string s = @"^([\w\.]+)@[\w]+(\.[\w]+)+$";
            Regex re = new Regex(s);
            return re.IsMatch(emailAddress);
        }

        #endregion

        #region 验证正整数
        /// <summary>
        /// 验证正整数
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static bool ValidateInt(string str)
        {
            string s = @"^[0-9]*[1-9][0-9]*$";
            Regex re = new Regex(s);
            return re.IsMatch(str);
        }

        #endregion

        #region 验证非负整数
        /// <summary>
        /// 验证非负整数
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static bool ValidateInt2(string str)
        {
            string s = @"^\d+$";
            Regex re = new Regex(s);
            return re.IsMatch(str);
        }

        #endregion

        #region 验证电话号码
        /// <summary>
        /// 验证电话号码
        /// </summary>
        /// <param name="emailAddress">待验证的电话号码</param>
        /// <returns>电话号码是否合法</returns>
        public static bool ValidatePhoneNumber(string phoneNumber)
        {
            string s = @"^(\+[\d]{1,2})?[\s]*(\([\d]{1,3}\))?([\d\s\-]{3,})$";
            Regex re = new Regex(s);
            return re.IsMatch(phoneNumber);
        }
        #endregion

        #region 绑定下拉列表控件（日期）
        /// <summary>
        /// 绑定下拉列表控件（日期）（显示空行标题）
        /// </summary>
        /// <param name="_ObjectName">控件ID</param>
        /// <param name="_dt">进行绑定的数据表</param>
        /// <param name="_ValueField">值字段</param>
        /// <param name="_TextField">显示字段</param>
        /// <param name="_SelectValue">选中的值</param>
        /// <param name="_Head">标题</param>
        public static void DropDownListBind(System.Web.UI.WebControls.DropDownList _ObjectName, string _Class)
        {

            if (_Class == "Year")
            {
                System.Web.UI.WebControls.ListItem _Item = new ListItem("--选择年--", "0");
                _ObjectName.Items.Add(_Item);
                _Item = null;

                for (int i = 2004; i <= 2015; i++)
                {
                    System.Web.UI.WebControls.ListItem _Item2 = new ListItem(i.ToString() + "年", i.ToString());
                    _ObjectName.Items.Add(_Item2);
                    _Item2 = null;
                }

            }

            if (_Class == "Month")
            {
                System.Web.UI.WebControls.ListItem _Item = new ListItem("--选择月--", "0");
                _ObjectName.Items.Add(_Item);
                _Item = null;
                for (int i = 1; i <= 12; i++)
                {
                    System.Web.UI.WebControls.ListItem _Item2 = new ListItem(i.ToString() + "月", i.ToString());
                    _ObjectName.Items.Add(_Item2);
                    _Item2 = null;
                }

            }

            if (_Class == "Day")
            {
                System.Web.UI.WebControls.ListItem _Item = new ListItem("--选择日--", "0");
                _ObjectName.Items.Add(_Item);
                _Item = null;
                for (int i = 1; i <= 31; i++)
                {
                    System.Web.UI.WebControls.ListItem _Item2 = new ListItem(i.ToString() + "日", i.ToString());
                    _ObjectName.Items.Add(_Item2);
                    _Item2 = null;
                }

            }

        }
        #endregion

        #region 返回最后分隔符后面的字符串
        /// <summary>
        /// 返回最后分隔符后面的字符串
        /// </summary>
        /// <param name="LookFor">分隔符</param>
        /// <param name="myString">被查询字符串</param>
        /// <returns></returns>
        public static string GetLastRightOf(string LookFor, string myString)
        {
            int StrPos;
            StrPos = myString.LastIndexOf(LookFor);
            return myString.Substring(StrPos + 1);
        }
        #endregion

        #region 绑定下拉列表控件（显示空行标题）
        /// <summary>
        /// 绑定下拉列表控件（显示空行标题）
        /// </summary>
        /// <param name="_ObjectName">控件ID</param>
        /// <param name="_dt">进行绑定的数据表</param>
        /// <param name="_ValueField">值字段</param>
        /// <param name="_TextField">显示字段</param>
        /// <param name="_SelectValue">选中的值</param>
        /// <param name="_Head">标题</param>
        public static void DropDownListBind(System.Web.UI.WebControls.DropDownList _ObjectName, DataTable _dt, string _ValueField,
            string _TextField, string _SelectValue, string _Head)
        {
            _ObjectName.DataSource = _dt;

            _ObjectName.DataTextField = _TextField;

            _ObjectName.DataValueField = _ValueField;

            _ObjectName.DataBind();

            bool _Selected = false;

            if (_SelectValue.Trim().Length > 0)
            {
                foreach (System.Web.UI.WebControls.ListItem SelItem in _ObjectName.Items)
                {
                    if (SelItem.Value.Trim() == _SelectValue.Trim())
                    {
                        SelItem.Selected = true;

                        _Selected = true;

                        break;
                    }
                }
            }

            System.Web.UI.WebControls.ListItem FirstItem = new ListItem();

            FirstItem.Text = _Head;

            FirstItem.Value = "";

            _ObjectName.Items.Insert(0, FirstItem);

            if (!_Selected)
            {
                FirstItem.Selected = true;
            }
        }
        #endregion

        #region 绑定下拉列表控件
        /// <summary>
        /// 绑定下拉列表控件
        /// </summary>
        /// <param name="_ObjectName">控件ID</param>
        /// <param name="_dt">进行绑定的数据表</param>
        /// <param name="_ValueField">值字段</param>
        /// <param name="_TextField">显示字段</param>
        /// <param name="_SelectValue">选中的值</param>
        public static void DropDownListBind(System.Web.UI.WebControls.DropDownList _ObjectName, DataTable _dt, string _ValueField,
            string _TextField, string _SelectValue)
        {
            _ObjectName.DataSource = _dt;

            _ObjectName.DataTextField = _TextField;

            _ObjectName.DataValueField = _ValueField;

            _ObjectName.DataBind();

            if (_SelectValue.Trim().Length > 0)
            {
                foreach (System.Web.UI.WebControls.ListItem SelItem in _ObjectName.Items)
                {
                    if (SelItem.Value.Trim() == _SelectValue.Trim())
                    {
                        SelItem.Selected = true;
                    }
                }
            }


        }

        public static void DropDownBind(System.Web.UI.WebControls.DropDownList _ObjectName, string _SelectValue)
        {
            foreach (ListItem item2 in _ObjectName.Items)
            {
                if (item2.Value == _SelectValue)
                {
                    item2.Selected = true;
                    break;
                }
            }

        }

        #endregion

        #region 分隔字符串为数组
        /// <summary>
        /// 分隔字符串为数组
        /// </summary>
        /// <param name="_split">被分组的字符串</param>
        /// <param name="_blank">分隔字符串</param>
        /// <returns>返回一个数组</returns>
        public static ArrayList TranSplit(string _split, string _blank)
        {
            ArrayList _Array = new ArrayList();

            string _split2 = "";

            while (_split.IndexOf(_blank, 0) > -1)
            {
                _split2 = _split.Substring(0, _split.IndexOf(_blank, 0));
                _Array.Add(_split2);
                _split = _split.Substring(_split.IndexOf(_blank, 0) + _blank.Length, _split.Length
                    - _split.IndexOf(_blank, 0) - _blank.Length);
            }

            if (_split.Trim().Length > 0)
            {
                _Array.Add(_split);
            }

            return _Array;
        }

        #endregion

        #region 返回弹出信息
        /// <summary>
        /// 返回弹出信息
        /// </summary>
        /// <param name="_Message">信息字符串</param>
        /// <returns>返回弹出信息</returns>
        public static string JsShowMessage(string _Message)
        {
            string _JS;

            _JS = "<script language=javascript>alert(\"" + _Message + "\");return false;</script>";

            return _JS;
        }
        #endregion

        #region 显示日期的年月日
        public static string TranDate(string _Date)
        {
            DateTime _Date1 = Convert.ToDateTime(_Date);
            return _Date1.Year.ToString() + "-" + _Date1.Month.ToString() + "-" + _Date1.Day.ToString();
        }
        public static string TranDate(DateTime _Date)
        {
            return _Date.Year.ToString() + "-" + _Date.Month.ToString() + "-" + _Date.Day.ToString();
        }
        public static string TranDateTrim(DateTime _Date)
        {
            return _Date.Year.ToString() + _Date.Month.ToString() + _Date.Day.ToString();
        }
        #endregion

        #region 验证数值型转换是否成功
        public static bool TranDec(string _Value)
        {
            bool _Return = true;

            if (_Value.Trim().Length > 0)
            {
                Decimal _Last = Convert.ToDecimal(_Value);
                if (_Last == 0 || _Last < 0)
                {
                    _Return = false;
                }
            }
            else
            {
                _Return = false;
            }

            return _Return;
        }

        public static bool TranInt(string _Value)
        {
            bool _Return = true;

            if (_Value.Trim().Length > 0)
            {
                Decimal _Last = Convert.ToInt32(_Value);
                if (_Last == 0 || _Last < 0)
                {
                    _Return = false;
                }
            }
            else
            {
                _Return = false;
            }

            return _Return;
        }
        #endregion

        #region 文件IO
        /// <summary>
        /// 建立文件
        /// </summary>
        /// <param name="_sName">文件路径</param>
        public static void Create_File(string _sName)
        {
            // Create the new, empty data file.
            if (File.Exists(_sName))
            {
                return;
            }

            FileStream fs = new FileStream(_sName, FileMode.CreateNew);
            // Create the writer for data.
            BinaryWriter w = new BinaryWriter(fs);
            // Write data to Test.data.
            for (int i = 0; i < 11; i++)
            {
                w.Write((int)i);
            }
            w.Close();
            fs.Close();
        }

        /// <summary>
        /// 读取文件所有内容
        /// </summary>
        /// <param name="_sName">文件路径</param>
        /// <returns>返回内容</returns>
        public static string Read_File(string _sName)
        {
            string _sReturn = "";
            if (!File.Exists(_sName))
            {
                return _sReturn;
            }

            StreamReader sr = File.OpenText(_sName);

            _sReturn = sr.ReadToEnd();

            sr.Close();
            return _sReturn;

        }

        /// <summary>
        /// 写入内容
        /// </summary>
        /// <param name="_sName">路径</param>
        /// <param name="_sContent">内容</param>
        public static void Write_File(string _sName, string _sContent)
        {
            if (!File.Exists(_sName))
            {
                return;
            }

            using (StreamWriter sw = new StreamWriter(_sName))
            {
                sw.Write(_sContent);
            }

        }

        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="_sName">文件路径</param>
        /// <returns></returns></returns>
        public static void Delete_File(string _sName)
        {
            if (File.Exists(_sName))
            {
                File.Delete(_sName);
                return;
            }

        }

        #endregion

        #region 星期一日期
        public static DateTime WeekFirstDate()
        {
            string Day = DateTime.Now.DayOfWeek.ToString();
            DateTime Return = DateTime.Now;

            switch (Day)
            {
                case "Monday":
                    Return = Return.AddDays(-1);
                    break;
                case "Tuesday":
                    Return = Return.AddDays(-2);
                    break;
                case "Wednesday":
                    Return = Return.AddDays(-3);
                    break;
                case "Thursday":
                    Return = Return.AddDays(-4);
                    break;
                case "Friday":
                    Return = Return.AddDays(-5);
                    break;
                case "Saturday":
                    Return = Return.AddDays(-6);
                    break;
                case "Sunday":
                    break;
            }

            return Return;
        }
        #endregion

        #region 本地smtp发送Email
        /// <summary>
        /// 本地smtp发送Email
        /// </summary>
        /// <param name="MailTo">接收Email地址</param>
        /// <param name="MailFrom">发送翻Email地址</param>
        /// <param name="MailSubject">邮件主题</param>
        /// <param name="MailBody">邮件内容</param>
        /// <param name="isHtml">是否为Html格式</param>
        /// <returns>布尔值表示发送成功与否</returns>
        public static bool SendEmail(string MailTo, string MailSubject, string MailBody)
        {
            string MailFrom = System.Configuration.ConfigurationSettings.AppSettings["FromEmail"].ToString();
            MailMessage myMail = new MailMessage(MailFrom, MailTo);
            SmtpClient smtp = new SmtpClient();
            bool isReturn = false;

            try
            {
                myMail.BodyEncoding = Encoding.GetEncoding("utf-8");
                myMail.IsBodyHtml = false;
                myMail.Subject = MailSubject;
                myMail.Body = MailBody;
                myMail.Priority = MailPriority.High;
                smtp.Host = System.Configuration.ConfigurationSettings.AppSettings["SMTP"].ToString();

                smtp.Send(myMail);

                isReturn = true;
            }
            catch
            {

            }

            return isReturn;

        }
        #endregion

        #region 邮箱格式检查
        /// <summary>
        /// 邮箱格式检查
        /// </summary>
        /// <param name="str">邮箱地址</param>
        /// <returns>true/false</returns>
        public static bool EmailFormatChk(string str)
        {
            Regex r = new Regex(@"^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$");
            return r.IsMatch(str);
        }
        #endregion

        #region 获取GUID号
        /// <summary>
        /// 获取GUID号
        /// </summary>
        /// <returns>返回新的GUID号</returns>
        public static string GetNewGuid()
        {
            Guid aGuid = Guid.NewGuid();
            return aGuid.ToString("D");
        }
        #endregion

        #region 过滤字符串
        /// <summary>
        /// 过滤字符串
        /// </summary>
        /// <param name="str">传入字符串</param>
        /// <returns>返回安全字符串</returns>
        public static string EnCodeStr(string str)
        {
            string tmp = str;
            if (tmp == "" || tmp == null)
                return tmp;
            tmp = HttpContext.Current.Server.HtmlEncode(tmp);
            if (tmp.IndexOf("'", 0) != -1)
            {
                tmp = tmp.Replace("'", "''");
            }
            return tmp;
        }
        #endregion

        #region 显示换行效果
        /// <summary>
        /// 显示换行效果
        /// </summary>
        /// <param name="str">传入字符串</param>
        /// <returns>返回换行效果</returns>
        public static string TextObjToText(string str)
        {
            string tmp = str;
            if (tmp == "" || tmp == null)
                return tmp;
            tmp = tmp.Replace("\n", "<br>");
            return tmp;
        }
        #endregion

        #region 客户端脚本操作代码

        /// <summary>
        ///写客户端JavaScript脚本函数 
        /// </summary>
        /// <param name="JSString">脚本内容</param>
        public static void WriteJS(string JSString)
        {
            HttpContext.Current.Response.Write("<Script Language=JavaScript>\n\r<!--\n\r");
            HttpContext.Current.Response.Write(JSString.Replace("\r", "\\r").Replace("\n", "\\n"));
            HttpContext.Current.Response.Write("\n\r//-->\n\r</Script>\n\r");
        }

        /// <summary>
        /// 写客户端VBScript脚本函数
        /// </summary>
        /// <param name="VBSString">脚本内容</param>
        public static void WriteVBS(string VBSString)
        {

            HttpContext.Current.Response.Write("<Script Language=VBScript>\n\r<!--\n\r");
            HttpContext.Current.Response.Write(VBSString);
            HttpContext.Current.Response.Write("\n\r'-->\n\r</Script>\n\r");
        }


        /// <summary>
        /// 显示客户端用户警告信息函数
        /// </summary>
        /// <param name="strAlert">警告信息内容</param>
        public static void Alert(object strAlert)
        {
            WriteJS("alert('" + strAlert.ToString().Replace("'", "\\'") + "');");
        }
        #endregion

        #region 导出Excel
        /// <summary>
        /// 导出Excel
        /// </summary>
        /// <param name="ctl"></param>
        /// <param name="FileName"></param>
        public static void ControlToExcel(System.Web.UI.Control ctl, string FileName)
        {
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.Buffer = true;
            HttpContext.Current.Response.Charset = "gb2312";
            HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8) + ".xls");
            HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
            HttpContext.Current.Response.ContentType = "application/ms-excel";
            HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + "" + FileName + ".xls");
            ctl.Page.EnableViewState = false;
            System.IO.StringWriter tw = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
            ClearControls(ctl);
            ctl.RenderControl(hw);
            HttpContext.Current.Response.Write(tw.ToString());
            HttpContext.Current.Response.End();
        }
        #endregion

        #region 清除控件中的所有控件，以便导出Excel
        /// <summary>
        /// 清除控件中的所有控件，以便导出Excel
        /// </summary>
        /// <param name="control"></param>
        private static void ClearControls(Control control)
        {
            for (int i = control.Controls.Count - 1; i >= 0; i--)
            {
                ClearControls(control.Controls[i]);
            }

            if (!(control is TableCell))
            {
                if (control.GetType().GetProperty("SelectedItem") != null)
                {
                    LiteralControl literal = new LiteralControl();
                    control.Parent.Controls.Add(literal);
                    try
                    {
                        literal.Text = (string)control.GetType().GetProperty("SelectedItem").GetValue(control, null);
                    }
                    catch
                    {
                    }
                    control.Parent.Controls.Remove(control);
                }
                else if (control.GetType().GetProperty("Text") != null)
                {
                    LiteralControl literal = new LiteralControl();
                    control.Parent.Controls.Add(literal);
                    literal.Text = (string)control.GetType().GetProperty("Text").GetValue(control, null);
                    control.Parent.Controls.Remove(control);
                }
            }
            return;
        }
        #endregion

        #region 将datatable中的数据导出到指定的excel文件中
        /// <summary> 
        /// 将datatable中的数据导出到指定的excel文件中 
        /// </summary> 
        /// <param name="page">web页面对象</param> 
        /// <param name="tab">包含被导出数据的datatable对象</param> 
        /// <param name="filename">excel文件的名称</param> 
        public static void ExportToExcel(System.Web.UI.Page page, System.Data.DataTable tab, string filename)
        {
            System.Web.HttpResponse httpresponse = page.Response;
            System.Web.UI.WebControls.DataGrid datagrid = new DataGrid();
            datagrid.DataSource = tab.DefaultView;
            datagrid.AllowPaging = false;
            datagrid.HeaderStyle.BackColor = System.Drawing.Color.Gray;
            datagrid.HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
            datagrid.HeaderStyle.Font.Bold = true;
            datagrid.DataBind();
            httpresponse.AppendHeader("content-disposition", "inline;attachment;filename=" + HttpUtility.UrlEncode(filename, System.Text.Encoding.UTF8)); //filename="*.xls"; 
            httpresponse.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
            httpresponse.ContentType = "application/ms-excel";
            System.IO.StringWriter tw = new StringWriter();
            System.Web.UI.HtmlTextWriter hw = new HtmlTextWriter(tw);
            datagrid.RenderControl(hw);

            HttpContext.Current.Response.Write(tw.ToString());

            //string filepath = page.Server.MapPath("..") + "\\ExportFiles\\" + filename;
            //System.IO.StreamWriter sw = System.IO.File.CreateText(filepath);
            //sw.Write(tw.ToString());
            //sw.Close();

            //DownFile(httpresponse, filename, filepath);

            httpresponse.End();
        }
        #endregion

        #region 下载文件
        /// <summary>
        /// 下载
        /// </summary>
        /// <param name="response"></param>
        /// <param name="filename"></param>
        /// <param name="fullpath"></param>
        /// <returns></returns>
        private static bool DownFile(System.Web.HttpResponse response, string filename, string fullpath)
        {
            try
            {
                response.ContentType = "application/octet-stream";

                response.AppendHeader("content-disposition", "attachment;filename=" +
                HttpUtility.UrlEncode(filename, System.Text.Encoding.UTF8) + ";charset=gb2312");
                System.IO.FileStream fs = System.IO.File.OpenRead(fullpath);
                long flen = fs.Length;
                int size = 102400;//每100k同时下载数据 
                byte[] readdata = new byte[size];//指定缓冲区的大小 
                if (size > flen) size = Convert.ToInt32(flen);
                long fpos = 0;
                bool isend = false;
                while (!isend)
                {
                    if ((fpos + size) > flen)
                    {
                        size = Convert.ToInt32(flen - fpos);
                        readdata = new byte[size];
                        isend = true;
                    }
                    fs.Read(readdata, 0, size);//读入一个压缩块 
                    response.BinaryWrite(readdata);
                    fpos += size;
                }
                fs.Close();
                System.IO.File.Delete(fullpath);
                return true;
            }
            catch
            {
                return false;
            }
        }
        #endregion

        #region  DataTable 操作公用方法
        /// <summary>
        /// 返回执行Select distinct后的DataTable
        /// </summary>
        /// <param name="SourceTable">源数据表</param>
        /// <param name="FieldNames">字段集</param>
        /// <returns></returns>
        public static DataTable SelectDistinct(DataTable SourceTable, params string[] FieldNames)
        {
            object[] lastValues;
            DataTable newTable;
            DataRow[] orderedRows;

            if (FieldNames == null || FieldNames.Length == 0)
                throw new ArgumentNullException("FieldNames");

            lastValues = new object[FieldNames.Length];
            newTable = new DataTable();

            foreach (string fieldName in FieldNames)
                newTable.Columns.Add(fieldName, SourceTable.Columns[fieldName].DataType);

            orderedRows = SourceTable.Select("", string.Join(",", FieldNames));

            foreach (DataRow row in orderedRows)
            {
                if (!fieldValuesAreEqual(lastValues, row, FieldNames))
                {
                    newTable.Rows.Add(createRowClone(row, newTable.NewRow(), FieldNames));

                    setLastValues(lastValues, row, FieldNames);
                }
            }

            return newTable;
        }

        private static bool fieldValuesAreEqual(object[] lastValues, DataRow currentRow, string[] fieldNames)
        {
            bool areEqual = true;

            for (int i = 0; i < fieldNames.Length; i++)
            {
                if (lastValues[i] == null || !lastValues[i].Equals(currentRow[fieldNames[i]]))
                {
                    areEqual = false;
                    break;
                }
            }

            return areEqual;
        }

        private static DataRow createRowClone(DataRow sourceRow, DataRow newRow, string[] fieldNames)
        {
            foreach (string field in fieldNames)
                newRow[field] = sourceRow[field];

            return newRow;
        }

        private static void setLastValues(object[] lastValues, DataRow sourceRow, string[] fieldNames)
        {
            for (int i = 0; i < fieldNames.Length; i++)
                lastValues[i] = sourceRow[fieldNames[i]];
        }
        #endregion
    }
}
